﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Xml;
using CustomControl;
using ListViewDragDrop.ServiceProviders.UI;
using log4net;
using Microsoft.VisualBasic;
using System;
using TeacherLeftHand.DataAccess;
using TeacherLeftHand.DocEditor;
//using TeacherLeftHand.Frameworks.DragDropFrameWork;
//using TeacherLeftHand.Frameworks.DragDropFrameWorkData;
using TeacherLeftHand.Model;
using TeacherLeftHand.Util;
using TeacherLeftHand.View;


public partial class DocumentEditor : UserControl
{


    private string _filePath = null;
    public string DocumentName = null;
    public double ZoomLevel = 1;
    public RichTextEditor editor;
    private bool isInlineRtbGotFocused = false;
    public TeachingPlanDocument teachingPlan;
    //public BlankDocument blankDocument;
    protected static readonly ILog Log = LogManager.GetLogger(typeof(MainWindow));
    public DocumentEditor(bool isBlank)
    {
        InitializeComponent();
        this.AddHandler(RichTextEditor.FocusEvent, new RoutedEventHandler(Focus_Handler));
        this.AddHandler(InlineRichTextBox.InlineRtbLostFocusEvent, new RoutedEventHandler(LostFocus_Handler));
        // this.Loaded += new RoutedEventHandler(DocumentEditor_Loaded);
        //if (!isBlank)
        //{
            teachingPlan = new TeachingPlanDocument();
            dockPanel.Children.Add(teachingPlan);
            this.editor = teachingPlan.rtbObjective;
        //}
        //else
        //{
        //    blankDocument = new BlankDocument();
        //    dockPanel.Children.Add(blankDocument);
        //    this.editor = blankDocument.rtbEditor;
        //}

    }
    public string FilePath
    {
        get { return _filePath; }
        set { _filePath = value; }
    }

    private void LostFocus_Handler(object sender, RoutedEventArgs e)
    {
        isInlineRtbGotFocused = false;
    }

    private void Focus_Handler(object sender, RoutedEventArgs e)
    {
        if (e.OriginalSource is InlineRichTextBox)
        {
            isInlineRtbGotFocused = true;
            this.editor = (RichTextEditor)e.OriginalSource;
        }
        else if (e.OriginalSource is RichTextEditor)
        {
            if (!isInlineRtbGotFocused)
            {
                this.editor = (RichTextEditor)e.OriginalSource;
            }
        }

    }

    #region LoadDocument

    public bool LoadDocument(string filename)
    {
        bool flag = false;
        try
        {
            var fileInfo = new System.IO.FileInfo(filename);
            //var fileStream = System.IO.File.Open(fileInfo.FullName, System.IO.FileMode.Open);
            //var textRange = new TextRange(editor.Document.ContentStart, editor.Document.ContentEnd);
            var parent = (DocumentTab)Parent;
            
            if (fileInfo.Extension == ".tlhx")
            {
                //var content = System.Windows.Markup.XamlReader.Load(fileStream) as FlowDocument;
                //editor.Document = content;
                try
                {
                    var plan = TeachingPlanAccessor.Load(filename);

                    if (plan != null)
                    {

                        // NewDocument(Path.GetFileName(filename));
                        // DocumentName = filename;
                        FilePath = filename;
                        teachingPlan.FileChanged = true;
                        teachingPlan.dtpTPComposeDate.SelectedDate = plan.ComposeDate;
                        teachingPlan.dtpTPTeachingDate.SelectedDate = plan.TeachingDate;
                        teachingPlan.cmbTPClass.Text = plan.ClassLevel + "";
                        teachingPlan.cmbTPSubject.Text = plan.Subject + "";
                        teachingPlan.cmbTPTopic.Text = plan.Topic + "";
                        teachingPlan.cmbTPTopicNumber.Text = plan.TopicNo + "";
                        teachingPlan.tbxTPSessionNumber.Text = plan.Session + "";
                        teachingPlan.tbxTPWeek.Text = plan.Week + "";
                        teachingPlan.rtbObjective.Document =
                            (FlowDocument)XamlReader.Load(new XmlTextReader(new StringReader((string)plan.Objective)));
                        XMLUtilitizer.Transform64ToImage(teachingPlan.rtbObjective.Document);
                        teachingPlan.rtbPreparation.Document =
                           (FlowDocument)XamlReader.Load(new XmlTextReader(new StringReader((string)plan.Preparation)));
                        XMLUtilitizer.Transform64ToImage(teachingPlan.rtbPreparation.Document);
                        LoadActivity(plan.Activities);
                        teachingPlan.rtbExperianceNote.Document =
                             (FlowDocument)XamlReader.Load(new XmlTextReader(new StringReader((string)plan.Note)));
                        XMLUtilitizer.Transform64ToImage(teachingPlan.rtbExperianceNote.Document);
                        flag = true;

                    }
                    else
                    {
                        MessageBox.Show("File Has Errors", "File Errors", MessageBoxButton.OK, MessageBoxImage.Warning);
                        flag = false;
                    }
                   
                }
                //catch(XamlParseException parseException)
                //{
                //    MessageBox.Show("File Has Errors", "File Has Errors", MessageBoxButton.OK, MessageBoxImage.Warning);
                //}
                catch (Exception ex)
                {
                    MessageBox.Show("File Has Errors", "File Errors", MessageBoxButton.OK, MessageBoxImage.Warning);
                    Log.Debug("Error in MainWindow.cs - " + "LoadFile - " + ex.Message);
                    flag = false;
                }
            }
            //else if (f.Extension == ".html" || f.Extension == ".htm")
            //{
            //    fs.Close();
            //    fs = null;
            //    try
            //    {
            //        //Dim content As FlowDocument = TryCast(Markup.XamlReader.Parse(HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(My.Computer.FileSystem.ReadAllText(filename), True)), FlowDocument)
            //        //Document = content hainh
            //    }
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show(ex.Message, "Error loading html document");
            //    }
            //}
            //else if (fileInfo.Extension == ".rtf")
            //{
            //    textRange.Load(fileStream, System.Windows.DataFormats.Rtf);
            //}
            //else
            //{
            //    textRange.Load(fileStream, System.Windows.DataFormats.Text);
            //}
            //if (fileStream != null)
            //{
            //    fileStream.Close();
            //    fileStream = null;
            //}
            if(flag)
            {
                DocumentName = filename;
                parent.SetDocumentTitle(fileInfo.Name);
                teachingPlan.FileChanged = false;
                
            }
            
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error loading document");
        }
        return flag;
    }

    private void LoadActivity(List<Activity> lstActivity)
    {
        try
        {

            var listofActivity = new ObservableCollection<ActivityView>();
            foreach (Activity activity in lstActivity)
            {

                var activityView = new ActivityView();
                activityView.rtbRtbActivityName.Text = activity.Name;
                activityView.rtbPurpose.Text = activity.Purpose;
                activityView.rtbMod.Text = activity.Form;

                var lstrtb = new ObservableCollection<RichTextEditor>();
                //var lstrtb = new List<RichTextBox>();
                foreach (var tm in activity.Content)
                {
                    var rtbTm = new RichTextEditor { Width = 620, IsDocumentEnabled = true };
                    rtbTm.Document = (FlowDocument)XamlReader.Load(new XmlTextReader(new StringReader((string)tm)));
                    XMLUtilitizer.Transform64ToImage(rtbTm.Document);

                    lstrtb.Add(rtbTm);
                }
                activityView.listOfTeachingMethod.ItemsSource = lstrtb;
                listofActivity.Add(activityView);

            }
            teachingPlan.listOfActivities.ItemsSource = listofActivity;

        }
        catch (Exception ex)
        {
            Log.Debug("Error in MainWindow.cs - " + "LoadActivity - " + ex.Message);
        }



    }
    #endregion

    #region SaveDocument

    public void SaveDocument()
    {
        try
        {
            //SaveTeachingPlan tlhx file
            //var teachingPlan = new TeachingPlan
            //{
            //    ClassLevel = SelectedDocument.Editor.cmbTPClass.SelectedValue != null ? Convert.ToInt32(SelectedDocument.Editor.cmbTPClass.SelectedValue.ToString()) : 1,
            //    ComposeDate = SelectedDocument.Editor.dtpTPComposeDate.SelectedDate != null ? SelectedDocument.Editor.dtpTPComposeDate.SelectedDate.Value : (DateTime?)null,
            //    TeachingDate = SelectedDocument.Editor.dtpTPTeachingDate.SelectedDate != null ? SelectedDocument.Editor.dtpTPTeachingDate.SelectedDate.Value : (DateTime?)null,
            //    Subject = SelectedDocument.Editor.cmbTPSubject.SelectedValue != null ? SelectedDocument.Editor.cmbTPSubject.SelectedValue.ToString() : "",
            //    Topic = SelectedDocument.Editor.cmbTPSubject.SelectedValue != null ? SelectedDocument.Editor.cmbTPSubject.SelectedValue.ToString() : "",
            //    TopicNo = SelectedDocument.Editor.cmbTPTopicNumber.SelectedValue != null ? Convert.ToInt32(SelectedDocument.Editor.cmbTPTopicNumber.Text) : 0,
            //    Session = String.IsNullOrEmpty(SelectedDocument.Editor.tbxTPSessionNumber.Text) ? 0 : Convert.ToInt32(SelectedDocument.Editor.tbxTPSessionNumber.Text.Trim()),
            //    Week = String.IsNullOrEmpty(SelectedDocument.Editor.tbxTPWeek.Text) ? 0 : Convert.ToInt32(SelectedDocument.Editor.tbxTPWeek.Text),
            //    Objective = RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.rtbObjective),
            //    Preparation = RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.rtbPreparation),
            //    Activities = RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.rtbPreparation),
            //    Note = RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.rtbExperianceNote)
            //};
            var file = new System.IO.FileInfo(FilePath);
            Log.Debug(TeachingPlanAccessor.Save(FilePath, GetTeachingPlan("Save")) ? "SaveTeachingPlan succeed " : "SaveTeachingPlan failed ");
            var p = (DocumentTab)Parent;
            DocumentName = file.Name;
            p.SetDocumentTitle(Path.GetFileName(file.Name));
            teachingPlan.FileChanged = false;
        }
        catch (Exception ex)
        {
            Log.Debug(ex.Message);
        }
    }

    #endregion
    private TeachingPlan GetTeachingPlan(string typeAction)
    {
        TeachingPlan plan = null;
        if (teachingPlan != null)
        {
            plan = new TeachingPlan
            {
                ClassLevel = teachingPlan.cmbTPClass.SelectedValue != null ? Convert.ToInt32(teachingPlan.cmbTPClass.SelectedValue.ToString()) : 1,
                ComposeDate = teachingPlan.dtpTPComposeDate.SelectedDate != null ? teachingPlan.dtpTPComposeDate.SelectedDate.Value : (DateTime?)null,
                TeachingDate = teachingPlan.dtpTPTeachingDate.SelectedDate != null ? teachingPlan.dtpTPTeachingDate.SelectedDate.Value : (DateTime?)null,
                Subject = teachingPlan.cmbTPSubject.SelectedValue != null ? teachingPlan.cmbTPSubject.SelectedValue.ToString() : teachingPlan.cmbTPSubject.Text,
                //Topic = teachingPlan.cmbTPTopic.SelectedValue != null ? teachingPlan.cmbTPTopic.SelectedValue.ToString() : teachingPlan.cmbTPTopic.Text,
                Topic = teachingPlan.cmbTPTopic.Text,
                TopicNo = teachingPlan.cmbTPTopicNumber.Value != null ? teachingPlan.cmbTPTopicNumber.Value.Value : 0,
                Session = teachingPlan.tbxTPSessionNumber.Value == null ? 0 : teachingPlan.tbxTPSessionNumber.Value.Value,
                Week = teachingPlan.tbxTPWeek.Value == null ? 0 : teachingPlan.tbxTPWeek.Value.Value,
                //Objective =  RichTextBoxProcessor.ConvertToString(teachingPlan.rtbObjective),
                Objective = XMLUtilitizer.ConvertFlowDocumentToSUBStringFormat(teachingPlan.rtbObjective.Document),
                Preparation = XMLUtilitizer.ConvertFlowDocumentToSUBStringFormat(teachingPlan.rtbPreparation.Document),
                Activities = GetActivity(typeAction),
                Note = XMLUtilitizer.ConvertFlowDocumentToSUBStringFormat(teachingPlan.rtbExperianceNote.Document)
            };

            //return teachingPlan;
        }

        return plan;

    }
    public List<Activity> GetActivity(string typeAction)
    {
        var lstActivity = new List<Activity>();
        for (int i = 0; i < teachingPlan.listOfActivities.Items.Count; i++)
        {
            var item = teachingPlan.listOfActivities.Items.GetItemAt(i);
            var activityView = item as ActivityView;
            if (activityView != null)
            {
                var lstTm = new List<object>();
                for (int j = 0; j < activityView.listOfTeachingMethod.Items.Count; j++)
                {
                    var richTextEditor = activityView.listOfTeachingMethod.Items.GetItemAt(j) as RichTextEditor;
                    if (richTextEditor != null)
                    {
                        object strTm;
                        if (typeAction.Trim().Equals("Export"))
                        {
                            strTm = RichTextBoxProcessor.GetInlineText(richTextEditor, typeAction);
                        }
                        else
                        {
                            //Clear Context Menu before save     
                            richTextEditor.ClearValue(RichTextEditor.ContextMenuProperty);
                            strTm = XMLUtilitizer.ConvertFlowDocumentToSUBStringFormat(richTextEditor.Document);
                        }
                        //if (!string.IsNullOrEmpty(strTm))
                        //{
                        //    lstTm.Add(strTm);
                        //}
                        if (strTm != null)
                        {
                            lstTm.Add(strTm);
                        }
                    }
                }


                var activity = new Activity
                {
                    Name = (activityView).rtbRtbActivityName.Text,
                    Purpose = (activityView).rtbPurpose.Text,
                    Form = (activityView).rtbMod.Text,
                    Content = lstTm
                };
                if (!string.IsNullOrEmpty(activity.Name) || !string.IsNullOrEmpty(activity.Purpose) || !string.IsNullOrEmpty(activity.Form) || activity.Content.Count > 0)
                {
                    lstActivity.Add(activity);
                }

            }
        }

        return lstActivity;
    }
    //private void DocumentEditor_TextChanged(object sender, TextChangedEventArgs e)
    //{
    //    if (FileChanged == false)
    //    {
    //        FileChanged = true;
    //    }
    //}


}